package com.bro.person;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author swallow
 * Created by swallow on 2018/12/12.<br>
 */
public class WordCount {

    /**
     * 读取
     */
    public static class MyMapper extends Mapper<LongWritable,Text,Text,LongWritable> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            LongWritable one = new LongWritable(1);
            String line = value.toString();
            String[] split = line.split(" ");
            for (String word :
                    split) {
                context.write(new Text(word),one);
            }
        }
    }

    public static class MyReduce extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value:
                 values) {
                sum += value.get();
            }
            context.write(key,new LongWritable(sum));
        }
    }

    /**
     * 定义 driver
     * @param args
     */
    public static void main(String[] args) throws Exception {

        //创建configuration
        Configuration configuration = new Configuration();

        Job job = Job.getInstance(configuration, "wordCount");
        //设置 job 的处理类
        job.setJarByClass(WordCount.class);
        // 设置 处理的输入路径
        FileInputFormat.setInputPaths(job,new Path(args[0]));

        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        job.setReducerClass(MyReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        FileOutputFormat.setOutputPath(job,new Path(args[1]));

        System.exit(job.waitForCompletion(true)?1:0);

    }

}
